﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDesktopServices>
#include <QUrl>
#include "clickedwidget.h"
#include "tools.h"
#include <QDebug>
#include "user.h"
#include <QMessageBox>
#include "company.h"
#include "dbhelper.h"
#include <QCloseEvent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("小微之家--云管理系统");

    clientPicker.setWidgetType(UserRelation::Client);
    giverPicker.setWidgetType(UserRelation::Giver);

    //初始化主界面点击事件
    initHomeSubWidgetClickEvent();

    initCompanyInfoWidgetState();

    initProductPageState();

    initSalePageState();

    initPurchasePageState();

    initMessagePageState();

    initFinancePageState();

    initBossPageState();

    connect(&productService, &ProductService::countProductSuccess,
            [=]()
    {
        ui->tableViewProductCount->clear();
    });

    connect(&productService, &ProductService::sanbaoMoveSuccess,
            [=]()
    {
        ui->tableViewProductLibrary->loadSanbaoProducts();
    });

    connect(&companyService, &CompanyService::updateCompanyDataSuccess,
            [=](double totalStore)
    {
        ui->labelBossTotalTicket->setText("发票总额:"+QString("%1").arg(Company::getTotalTicket()));
        ui->labelBossTotalMoney->setText("资金总额:"+QString("%1").arg(Company::getTotalMoney()));
        ui->labelBossTicketIn->setText("应收发票:"+QString("%1").arg(Company::getTicketIn()));
        ui->labelBossTicketOut->setText("应开发票:"+QString("%1").arg(Company::getTicketOut()));
        ui->labelBossMoneyIn->setText("应收货款:"+QString("%1").arg(Company::getMoneyIn()));
        ui->labelBossMoneyOut->setText("应付货款:"+QString("%1").arg(Company::getMoneyOut()));
        ui->labelBossQueryTotalStore->setText("库存总额:"+QString("%1").arg(totalStore));
        double taxRate = Company::getTaxRate().toDouble()/100;
        double totalHome = taxRate/(1+taxRate)*(Company::getTotalTicket()-Company::getTicketOut()+Company::getTicketIn());
        totalHome += Company::getTotalMoney()+Company::getMoneyIn()-Company::getMoneyOut()+totalStore;
        QPalette pa;
        pa.setColor(QPalette::WindowText,Qt::red);
        ui->labelBossQueryTotalHome->setText("合计家底:"+QString("%1").arg(totalHome));
        ui->labelBossQueryTotalHome->setPalette(pa);
    });

    connect(&messageService, &MessageService::getMessagesSuccess,
            [=](QList<Message*> messages)
    {
        ui->tableViewMessage->setData(messages);
        ui->lineEditMessageClientName->clear();
        ui->lineEditMessageContact->clear();
        ui->lineEditMessageTel->clear();
        ui->tableViewMessage->showData(
                    nullptr,
                    ui->comboBoxMessageType->currentIndex()+1);
    });

    connect(&addFinanceSubject, &AddFinanceSubject::addFinanceItemSuccess,
            [=]()
    {
        ui->tableViewFinanceKeep->getFinanceItems();
    });

    ui->commandLinkButtonClient->setUrl("http://122.51.166.114:8080/StoremsServer/user/download?fileName=client.xls");
    ui->commandLinkButtonGiver->setUrl("http://122.51.166.114:8080/StoremsServer/user/download?fileName=giver.xls");
    ui->commandLinkButtonProduct->setUrl("http://122.51.166.114:8080/StoremsServer/user/download?fileName=product.xls");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *ev){
    if(showExitMsg){
        int res = QMessageBox::question(this, "提示", "请检查是否有单据未保存，是否退出软件？", tr("确定"), tr("取消"));
        if(res == 0){
            ev->accept();
        }else{
            ev->ignore();
        }
    }else{
        ev->accept();
    }
}

void MainWindow::initHomeSubWidgetClickEvent()
{
    //销售页面事件
    connect(ui->widgetHomeSaleOut, &ClickedWidget::clicked, this, &MainWindow::on_actionSaleOut_triggered);
    connect(ui->widgetHomeSaleBack, &ClickedWidget::clicked, this, &MainWindow::on_actionSaleBack_triggered);
    connect(ui->widgetHomeClientManage, &ClickedWidget::clicked, this, &MainWindow::on_actionClientManage_triggered);
    connect(ui->widgetHomeSaleQuery, &ClickedWidget::clicked, this, &MainWindow::on_actionSaleQuery_triggered);
    connect(ui->widgetHomeSaleHistory, &ClickedWidget::clicked, this, &MainWindow::on_actionSaleHistory_triggered);
    //采购页面事件
    connect(ui->widgetHomePurchaseIn, &ClickedWidget::clicked, this, &MainWindow::on_actionPurchaseIn_triggered);
    connect(ui->widgetHomePurchaseBack, &ClickedWidget::clicked, this, &MainWindow::on_actionPurchaseBack_triggered);
    connect(ui->widgetHomeGiverManage, &ClickedWidget::clicked, this, &MainWindow::on_actionGiverManage_triggered);
    connect(ui->widgetHomePurchaseQuery, &ClickedWidget::clicked, this, &MainWindow::on_actionPurchaseQuery_triggered);
    connect(ui->widgetHomePurchaseOrder, &ClickedWidget::clicked, this, &MainWindow::on_actionPurchaseOrder_triggered);
    //库存页面事件
    connect(ui->widgetHomeProductStocks, &ClickedWidget::clicked, this, &MainWindow::on_actionProductStocks_triggered);
    connect(ui->widgetHomeProductSplit, &ClickedWidget::clicked, this, &MainWindow::on_actionProductSplit_triggered);
    connect(ui->widgetHomeProductCount, &ClickedWidget::clicked, this, &MainWindow::on_actionProductCount_triggered);
    connect(ui->widgetHomeProductLibrary, &ClickedWidget::clicked, this, &MainWindow::on_actionProductLibrary_triggered);
    connect(ui->widgetHomeProductPlan, &ClickedWidget::clicked, this, &MainWindow::on_actionProductPlan_triggered);
    //财政页面事件
    connect(ui->widgetHomeTicketOut, &ClickedWidget::clicked, this, &MainWindow::on_actionTicketOut_triggered);
    connect(ui->widgetHomeMoneyOut, &ClickedWidget::clicked, this, &MainWindow::on_actionMoneyOut_triggered);
    connect(ui->widgetHomeTicketIn, &ClickedWidget::clicked, this, &MainWindow::on_actionTicketIn_triggered);
    connect(ui->widgetHomeMoneyIn, &ClickedWidget::clicked, this, &MainWindow::on_actionMoneyIn_triggered);
    connect(ui->widgetHomeFinanceKeep, &ClickedWidget::clicked, this, &MainWindow::on_actionFinanceKeep_triggered);
    //老板页面事件
    connect(ui->widgetHomeBossQuery, &ClickedWidget::clicked, this, &MainWindow::on_actionBossQuery_triggered);
    connect(ui->widgetHomeFinanceQuery, &ClickedWidget::clicked, this, &MainWindow::on_actionFinanceQuery_triggered);
    connect(ui->widgetHomeProfitQuery, &ClickedWidget::clicked, this, &MainWindow::on_actionProfitQuery_triggered);
    connect(ui->widgetHomeTicketAdjust, &ClickedWidget::clicked, this, &MainWindow::on_actionTicketAdjust_triggered);
    connect(ui->widgetHomeBatch, &ClickedWidget::clicked, this, &MainWindow::on_actionBatch_triggered);

    connect(ui->labelBtnAdd, &ClickedLabel::clicked, this, &MainWindow::on_labelBtnAdd_clicked);
}

void MainWindow::initAfterLoginOK()
{
    showExitMsg = true;
    initPersonalInfo();
    ui->tableViewProduct->loadProucts();
    ui->treeViewProduct->initWithCategory(Company::getProductCategory(), "商品类别", "所有商品");
    ui->treeViewFinance->initCategory(Company::getFinanceCategory());
    ui->tableViewProductLibrary->loadSanbaoProducts();
    ui->widgetClientManage->loadCategory();
    ui->widgetClientManage->loadUserRelation();
    ui->widgetGiverManage->loadCategory();
    ui->widgetGiverManage->loadUserRelation();
    ui->tableViewCombineSplit->loadFormulas();
    ui->tableViewFinanceKeep->getFinanceItems();

    messageService.getMessages(this);
}

void MainWindow::initPersonalInfo()
{
    setWindowTitle("小微之家--云管理系统[用户："+User::getUsername()+"，企业ID："+(User::getCompanyId().isEmpty()?"无企业":User::getCompanyId())+"]");
    ui->lineEditNickName->setText(User::getNickName());
    ui->lineEditPosition->setText(User::getPosition());
    ui->lineEditTel->setText(User::getTel());
    ui->lineEditMobile->setText(User::getMobile());
    ui->lineEditQQ->setText(User::getQQ());
    ui->lineEditWechat->setText(User::getWechat());
    ui->labelPersonalCredit->setText("积分:"+QString("%1").arg(User::getCredit()));
    ui->labelPersonalEndDate->setText("有效日期:"+User::getEndDate());
    if(User::getCompanyId().isEmpty()){
        ui->pushButtonSaveCompany->hide();
        Company::setProductCategory("");
        Company::setClientCategory("");
        Company::setGiverCategory("");
        Company::setFinanceCategory("");
    }else {
        initCompanyInfo();
        if(!User::getIsBoss()){
            //当前用户不是老板
            ui->pushButtonSaveCompany->hide();
        }
        ui->pushButtonNewCompany->hide();
        ui->pushButtonJoinCompany->hide();
    }
}

void MainWindow::initCompanyInfo()
{
    ui->lineEditCompanyId->setText(Company::getCompanyId());
    ui->lineEditTaxRate->setText(Company::getTaxRate());
    ui->lineEditCompanyName->setText(Company::getCompanyName());
    ui->lineEditContact->setText(Company::getContact());
    ui->lineEditCompanyTel->setText(Company::getTel());
    ui->lineEditFax->setText(Company::getFax());
    ui->lineEditWebsite->setText(Company::getWebsite());
    ui->lineEditEmail->setText(Company::getEmail());
    ui->lineEditProvince->setText(Company::getProvince());
    ui->lineEditCity->setText(Company::getCity());
    ui->lineEditDistrict->setText(Company::getDistrict());
    ui->lineEditAddress->setText(Company::getAddress());
    QString account = Company::getAccount();
    QStringList accounts = account.split("#");
    qDebug()<<accounts.size();
    if(accounts.size() > 0){
        ui->lineEditReceiptAccount->setText(accounts[0]);
    }
    if(accounts.size() > 1){
        ui->lineEditReceiptAccount1->show();
        ui->lineEditReceiptAccount1->setText(accounts[1]);
    }
    if(accounts.size() > 2){
        ui->lineEditReceiptAccount2->show();
        ui->lineEditReceiptAccount2->setText(accounts[2]);
    }
    if(accounts.size() > 3){
        ui->lineEditReceiptAccount3->show();
        ui->lineEditReceiptAccount3->setText(accounts[3]);
    }
    if(accounts.size() > 4){
        ui->lineEditReceiptAccount4->show();
        ui->lineEditReceiptAccount4->setText(accounts[4]);
    }
    ui->lineEditIntroduction->setText(Company::getIntroduction());
    ui->lineEditTicketCompanyName->setText(Company::getTicketCompanyName());
    ui->lineEditTaxNum->setText(Company::getTaxNum());
    ui->lineEditBank->setText(Company::getBank());
    ui->lineEditTicketAccount->setText(Company::getTicketAccount());
    ui->lineEditTicketTel->setText(Company::getTicketTel());
    ui->lineEditTicketAddress->setText(Company::getTicketAddress());

    companyService.updateCompanyData(this, false);
}

void MainWindow::initCompanyInfoWidgetState()
{
    setTabOrder(ui->lineEditCompanyId, ui->lineEditTaxRate);
    setTabOrder(ui->lineEditTaxRate, ui->lineEditCompanyName);
    setTabOrder(ui->lineEditCompanyName, ui->lineEditContact);
    setTabOrder(ui->lineEditContact, ui->lineEditCompanyTel);
    setTabOrder(ui->lineEditCompanyTel, ui->lineEditFax);
    setTabOrder(ui->lineEditFax, ui->lineEditWebsite);
    setTabOrder(ui->lineEditWebsite, ui->lineEditEmail);
    setTabOrder(ui->lineEditEmail, ui->lineEditProvince);
    setTabOrder(ui->lineEditProvince, ui->lineEditCity);
    setTabOrder(ui->lineEditCity, ui->lineEditDistrict);
    setTabOrder(ui->lineEditDistrict, ui->lineEditAddress);
    setTabOrder(ui->lineEditAddress, ui->lineEditReceiptAccount);
    setTabOrder(ui->lineEditReceiptAccount, ui->lineEditIntroduction);
    setTabOrder(ui->lineEditIntroduction, ui->lineEditTicketCompanyName);
    setTabOrder(ui->lineEditTicketCompanyName, ui->lineEditTaxNum);
    setTabOrder(ui->lineEditTaxNum, ui->lineEditBank);
    setTabOrder(ui->lineEditBank, ui->lineEditTicketAccount);
    setTabOrder(ui->lineEditTicketAccount, ui->lineEditTicketTel);
    setTabOrder(ui->lineEditTicketTel, ui->lineEditTicketAddress);

    connect(&companyService, &CompanyService::addCompanySuccess,
            [=]()
    {
        this->showExitMsg = false;
        this->close();
        emit this->showLogin();
    });

    connect(&joinCompanyWidget, &JoinCompanyWidget::joinCompanySuccess,
            [=]()
    {
        MainWindow::initCompanyInfo();
        ui->pushButtonNewCompany->hide();
        ui->pushButtonJoinCompany->hide();
        ui->pushButtonSaveCompany->show();
    });

    ui->lineEditReceiptAccount1->hide();
    ui->lineEditReceiptAccount2->hide();
    ui->lineEditReceiptAccount3->hide();
    ui->lineEditReceiptAccount4->hide();
}

void MainWindow::initProductPageState()
{
    newProductWidget.setWidgetType(SubmitProductWidget::NewProductWidget);
    updateProductWidget.setWidgetType(SubmitProductWidget::UpdateProductWidget);
    combineWidget.setWidgetTpe(CombineSplitWidget::CombineWidget);
    splitWidget.setWidgetTpe(CombineSplitWidget::SplitWidgetType);

    ui->tableViewProduct->setListPushButton(ui->pushButtonProductList);
    ui->tableViewProduct->initHiddenState();
    ui->tableViewProductPlan->setListPushButton(ui->pushButtonProductPlanList);
    ui->tableViewProductPlan->initHiddenState();
    ui->tableViewProductCount->setListPushButton(ui->pushButtonProductCountList);
    ui->tableViewProductCount->initHiddenState();
    ui->tableViewProductLibrary->setListPushButton(ui->pushButtonProductLibraryList);
    ui->tableViewProductLibrary->initHiddenState();

    connect(ui->treeViewProduct, &ProductTreeView::queryProducts,
            [=]()
    {
        productService.queryProducts(
                    ui->tableViewProduct,
                    ui->treeViewProduct,
                    ui->comboBoxProduct->currentIndex(),
                    ui->lineEditProductOverallQuery->text(),
                    ui->lineEditProductTypeQuery->text(),
                    ui->lineEditProductNameQuery->text());
    });

    connect(ui->tableViewProduct, &QTableView::doubleClicked,
            [=](const QModelIndex index)
    {
        Q_UNUSED(index);
        this->on_pushButtonEditProduct_clicked();
    });

    connect(ui->tableViewProduct, &ProductTableView::updateTotalValue,
            [=](int totalCount, int totalSanbao, double totalInprice)
    {
        ui->labelProductTotalCount->setText(QString("库存总数：%1").arg(totalCount));
        ui->labelProductTotalSanbao->setText(QString("三包总数：%1").arg(totalSanbao));
        ui->labelProductTotalInPrice->setText("净库存："+QString::number(totalInprice, 'f', 2)+"元");
    });

    connect(ui->tableViewProductCount, &ProductCountTableView::updateTotalValue,
            [=](int totalCount, double totalMoney)
    {
        ui->labelProductCountTotalPYPKSL->setText(QString("盘盈盘亏数量：%1").arg(totalCount));
        ui->labelProductCountTotalPYPKJE->setText("盘盈盘亏金额："+QString::number(totalMoney, 'f', 2)+"元");
    });

    connect(ui->tableViewProductLibrary, &ProductLibraryTableView::updateTotalValue,
            [=](int totalCount, double totalMoney)
    {
        ui->labelProductLibraryTotalCount->setText(QString("三包库存：%1").arg(totalCount));
        ui->labelProductLibraryTotalMoney->setText("三包库存金额："+QString::number(totalMoney, 'f', 2)+"元");
    });

    connect(&productService, &ProductService::updateFormulaSuccess,
            [=](QList<Formula*> formulas)
    {
        ui->tableViewCombineSplit->clear();
        ui->tableViewCombineSplit->insertFormula(formulas);
    });

    connect(ui->tableViewCombineSplit, &CombineSplitTableView::refreshFormula,
            [=]()
    {
        productService.updateFormulaData(this);
    });
}

void MainWindow::initSalePageState(){
    ui->widgetSaleQuery->setWidgetType(SaleQueryStandardItemModel::Sale);

    this->saleHistorySelectedUserRelation = nullptr;
    this->saleHistorySelectedProduct = nullptr;
    clientPicker.setWidgetType(UserRelation::Client);
    productPicker.setSelectionMode(QAbstractItemView::SingleSelection);

    connect(&clientPicker, &UserPicker::selectedFinished,
            [=](UserRelation *relation)
    {
        this->saleHistorySelectedUserRelation = relation;
        ui->lineEditSaleHistoryClientName->setText(relation->nickName);
        ui->lineEditSaleHistoryContact->setText(relation->contact);
        ui->lineEditSaleHistoryTel->setText(relation->tel);
    });

    connect(&productPicker, &ProductPicker::singleSelected,
            [=](Product *product, int defaultCount)
    {
        Q_UNUSED(defaultCount);
        this->saleHistorySelectedProduct = product;
        ui->lineEditSaleHistoryProductName->setText(product->name);
        ui->lineEditSaleHistoryProductType->setText(product->type);
        ui->lineEditSaleHistoryProductUnit->setText(product->unit);
    });

    connect(ui->lineEditSaleHistoryClientName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        clientPicker.loadData();
        clientPicker.exec();
    });

    connect(ui->lineEditSaleHistoryContact, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        clientPicker.loadData();
        clientPicker.exec();
    });

    connect(ui->lineEditSaleHistoryTel, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        clientPicker.loadData();
        clientPicker.exec();
    });

    connect(ui->lineEditSaleHistoryProductName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(ui->lineEditSaleHistoryProductType, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(ui->lineEditSaleHistoryProductUnit, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(&dingdanService, &DingdanService::getSaleHistoryProductsSuccess,
            [=](QList<HistoryProduct*> historyProducts)
    {
        ui->tableViewHistoryProductSale->clear();
        ui->tableViewHistoryProductSale->insertHistoryProduct(historyProducts);
    });

    ui->tableViewHistoryProductSale->setSortingEnabled(true);
    ui->tableViewHistoryProductSale->setListPushButton(ui->pushButtonSaleHistoryList);
    ui->tableViewHistoryProductSale->initHiddenState();
}

void MainWindow::initPurchasePageState(){
    ui->widgetPurchaseQuery->setWidgetType(SaleQueryStandardItemModel::Purchase);

    this->purchaseOrderSelectedUserRelation = nullptr;

    connect(&giverPicker, &UserPicker::selectedFinished,
            [=](UserRelation *relation)
    {
        this->purchaseOrderSelectedUserRelation = relation;
        ui->lineEditPurchaseOrderClientName->setText(relation->nickName);
        ui->lineEditPurchaseOrderContact->setText(relation->contact);
        ui->lineEditPurchaseOrderTel->setText(relation->tel);

        if(this->purchaseOrderSelectedUserRelation != nullptr){
            dingdanService.getHistoryProducts(
                        this,
                        1,
                        this->purchaseOrderSelectedUserRelation,
                        nullptr);
        }
    });

    connect(ui->lineEditPurchaseOrderClientName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        giverPicker.loadData();
        giverPicker.exec();
    });

    connect(ui->lineEditPurchaseOrderContact, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        giverPicker.loadData();
        giverPicker.exec();
    });

    connect(ui->lineEditPurchaseOrderTel, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        giverPicker.loadData();
        giverPicker.exec();
    });

    ui->tableViewPurchaseOrder->setListPushButton(ui->pushButtonPurchaseOrderList);
    ui->tableViewPurchaseOrder->initHiddenState();

    connect(&dingdanService, &DingdanService::getPurchaseHistoryProductsSuccess,
            [=](QList<HistoryProduct*> historyProducts)
    {
        ui->tableViewPurchaseOrder->clear();
        ui->tableViewPurchaseOrder->insertHistoryProduct(historyProducts);
    });

    connect(ui->tableViewPurchaseOrder, &PurchaseDingdanTableView::refreshTotalPlanCount,
            [=](int totalPlanCount)
    {
        ui->labelPurchaseOrderTotalCount->setText(QString("数量：%1").arg(totalPlanCount));
    });

    connect(&dingdanService, &DingdanService::calculateDingdanSuccess,
            [=]()
    {
        ui->pushButtonPurchaseOrderSend->setEnabled(true);
        ui->tableViewPurchaseOrder->clear();
        this->purchaseOrderSelectedUserRelation = nullptr;
        ui->lineEditPurchaseOrderClientName->clear();
        ui->lineEditPurchaseOrderContact->clear();
        ui->lineEditPurchaseOrderTel->clear();
    });
}

void MainWindow::initMessagePageState(){
    ui->tableViewMessage->setListPushButton(ui->pushButtonMessageList);
    ui->tableViewMessage->initHiddenState();

    this->messageSelectedUserRelation = nullptr;

    connect(ui->lineEditMessageClientName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        this->messagePageSelectUser();
    });

    connect(ui->lineEditMessageContact, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        this->messagePageSelectUser();
    });

    connect(ui->lineEditMessageTel, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        this->messagePageSelectUser();
    });

    connect(ui->tableViewMessage, &MessageTableView::updateTotalValue,
            [=](double totalTicket, double totalMoney)
    {
        if(ui->comboBoxMessageType->currentIndex() == 0){
            ui->labelMessageTotalTicket->setText("应开发票："+QString::number(totalTicket, 'f', 2));
            ui->labelMessageTotalMoney->setText("应收货款："+QString::number(totalMoney, 'f', 2));
        }else{
            ui->labelMessageTotalTicket->setText("应收发票："+QString::number(totalTicket, 'f', 2));
            ui->labelMessageTotalMoney->setText("应付货款："+QString::number(totalMoney, 'f', 2));
        }
    });

    connect(&messageUserPicker, &UserPicker::selectedFinished,
            [=](UserRelation *relation)
    {
        this->messageSelectedUserRelation = relation;
        ui->lineEditMessageClientName->setText(relation->nickName);
        ui->lineEditMessageContact->setText(relation->contact);
        ui->lineEditMessageTel->setText(relation->tel);

        ui->tableViewMessage->showData(
                    relation,
                    ui->comboBoxMessageType->currentIndex()+1);
    });
}

void MainWindow::messagePageSelectUser(){
    if(ui->comboBoxMessageType->currentIndex() == 0){
        //选择客户
        messageUserPicker.setWidgetType(UserRelation::Client);
    }else{
        //选择供应商
        messageUserPicker.setWidgetType(UserRelation::Giver);
    }

    messageUserPicker.loadData();
    messageUserPicker.exec();
}

void MainWindow::initFinancePageState(){
    ui->dateEditFinanceQueryStartTime->setDisplayFormat("yyyy-MM-dd");
    ui->dateEditFinanceQueryStartTime->setMinimumDate(Tools::getBaseDate());
    ui->dateEditFinanceQueryStartTime->setMaximumDate(QDate::currentDate());
    ui->dateEditFinanceQueryStartTime->setDate(Tools::getBaseDate());

    ui->dateEditFinanceQueryEndTime->setDisplayFormat("yyyy-MM-dd");
    ui->dateEditFinanceQueryEndTime->setMinimumDate(Tools::getBaseDate());
    ui->dateEditFinanceQueryEndTime->setMaximumDate(QDate::currentDate());
    ui->dateEditFinanceQueryEndTime->setDate(QDate::currentDate());

    lastFinanceQueryStartDate = Tools::getBaseDate();
    lastFinanceQueryEndDate = QDate::currentDate();

    financeQueryTypes.clear();
    QStringList type1 = {"全部", "开票", "收款", "收票", "付款", "票款调整"};
    QStringList type2 = {
        "全部", "商品批导入", "发票盘点", "资金盘点", "商品盘点", "拆分差价", "营外收入", "营外支出", "税率变更"};
    financeQueryTypes.append(type1);
    financeQueryTypes.append(type2);
    ui->comboBoxFinanceQueryType2->clear();
    ui->comboBoxFinanceQueryType2->addItems(type1);

    ui->tableViewFinanceQuery->setListPushButton(ui->pushButtonFinanceQueryList);
    ui->tableViewFinanceQuery->initMultiHiddenStateList();

    connect(&financeService, &FinanceService::financeQuerySuccess,
            [=](QList<Message*> messages)
    {
        ui->tableViewFinanceQuery->clear();
        ui->tableViewFinanceQuery->insertMessage(messages);
    });
}

void MainWindow::initBossPageState(){
    adjustTicketUserRelation = nullptr;

    ui->pushButtonTicketAdjustMoneyImport->setVisible(false);
    ui->pushButtonTicketAdjustTicketImport->setVisible(false);

    messagePicker.setWidgetType(MessagePickerStandardItemModel::TicketAdjust);

    connect(&messagePicker, &MessagePicker::importMessageSelected,
            [=](Message *message)
    {
        ticketMoneyAdjustWidget.showWithMessage(message);
    });

    connect(ui->lineEditTicketAdjustClientName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        if(ui->comboBoxTicketAdjustType->currentIndex() == 0){
            adjustTicketUserPicker.setWidgetType(UserRelation::Client);
        }else{
            adjustTicketUserPicker.setWidgetType(UserRelation::Giver);
        }

        adjustTicketUserPicker.loadData();
        adjustTicketUserPicker.exec();
    });

    connect(ui->lineEditTicketAdjustContact, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        if(ui->comboBoxTicketAdjustType->currentIndex() == 0){
            adjustTicketUserPicker.setWidgetType(UserRelation::Client);
        }else{
            adjustTicketUserPicker.setWidgetType(UserRelation::Giver);
        }

        adjustTicketUserPicker.loadData();
        adjustTicketUserPicker.exec();
    });

    connect(ui->lineEditTicketAdjustTel, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        if(ui->comboBoxTicketAdjustType->currentIndex() == 0){
            adjustTicketUserPicker.setWidgetType(UserRelation::Client);
        }else{
            adjustTicketUserPicker.setWidgetType(UserRelation::Giver);
        }

        adjustTicketUserPicker.loadData();
        adjustTicketUserPicker.exec();
    });

    connect(&adjustTicketUserPicker, &UserPicker::selectedFinished,
            [=](UserRelation *relation)
    {
        this->adjustTicketUserRelation = relation;
        ui->lineEditTicketAdjustClientName->setText(relation->nickName);
        ui->lineEditTicketAdjustContact->setText(relation->contact);
        ui->lineEditTicketAdjustTel->setText(relation->tel);
    });

    connect(&userRelationService, &UserRelationService::adjustUserRelationFinanceSuccess,
            [=]()
    {
        on_pushButtonTicketAdjustClear_clicked();
    });

    connect(ui->treeViewFinance, &FinanceTreeView::queryFinanceItem,
            [=](QString primaryDirectory, QString secondaryDirectory)
    {
        ui->tableViewFinanceKeep->queryFinanceItem(primaryDirectory, secondaryDirectory);
    });

    ui->widgetProfitQuery->setWidgetType(SaleQueryStandardItemModel::Profit);
}

void MainWindow::on_actionHome_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pageHome);
}

void MainWindow::on_actionSaleOut_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageSale);
        ui->tabWidgetSale->setCurrentWidget(ui->tabSaleOut);
    }
}

void MainWindow::on_actionSaleBack_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageSale);
        ui->tabWidgetSale->setCurrentWidget(ui->tabSaleBack);
    }
}

void MainWindow::on_actionClientManage_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageSale);
        ui->tabWidgetSale->setCurrentWidget(ui->tabClientManage);
    }
}

void MainWindow::on_actionSaleQuery_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageSale);
        ui->tabWidgetSale->setCurrentWidget(ui->tabSaleQuery);
    }
}

void MainWindow::on_actionSaleHistory_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageSale);
        ui->tabWidgetSale->setCurrentWidget(ui->tabSaleHistory);
    }
}

void MainWindow::on_actionPurchaseIn_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pagePurchase);
        ui->tabWidgetPurchase->setCurrentWidget(ui->tabPurchaseIn);
    }
}

void MainWindow::on_actionPurchaseBack_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pagePurchase);
        ui->tabWidgetPurchase->setCurrentWidget(ui->tabPurchaseBack);
    }
}

void MainWindow::on_actionGiverManage_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pagePurchase);
        ui->tabWidgetPurchase->setCurrentWidget(ui->tabGiverManage);
    }
}

void MainWindow::on_actionPurchaseQuery_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pagePurchase);
        ui->tabWidgetPurchase->setCurrentWidget(ui->tabPurchaseQuery);
    }
}

void MainWindow::on_actionPurchaseOrder_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pagePurchase);
        ui->tabWidgetPurchase->setCurrentWidget(ui->tabPurchaseOrder);
    }
}

void MainWindow::on_actionProductStocks_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageProduct);
        ui->tabWidgetProduct->setCurrentWidget(ui->tabProductStocks);
    }
}

void MainWindow::on_actionProductPlan_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageProduct);
        ui->tabWidgetProduct->setCurrentWidget(ui->tabProductPlan);
    }
}

void MainWindow::on_actionProductCount_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageProduct);
        ui->tabWidgetProduct->setCurrentWidget(ui->tabProductCount);
    }
}

void MainWindow::on_actionProductSplit_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageProduct);
        ui->tabWidgetProduct->setCurrentWidget(ui->tabProductSplit);
    }
}

void MainWindow::on_actionProductLibrary_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageProduct);
        ui->tabWidgetProduct->setCurrentWidget(ui->tabProductLibrary);
    }
}

void MainWindow::on_actionTicketOut_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageFinance);
        ui->tabWidgetFinance->setCurrentWidget(ui->tabTicketOut);
    }
}

void MainWindow::on_actionMoneyIn_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageFinance);
        ui->tabWidgetFinance->setCurrentWidget(ui->tabMoneyIn);
    }
}

void MainWindow::on_actionTicketIn_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageFinance);
        ui->tabWidgetFinance->setCurrentWidget(ui->tabTicketIn);
    }
}

void MainWindow::on_actionMoneyOut_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageFinance);
        ui->tabWidgetFinance->setCurrentWidget(ui->tabMoneyOut);
    }
}

void MainWindow::on_actionFinanceKeep_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageFinance);
        ui->tabWidgetFinance->setCurrentWidget(ui->tabFinanceKeep);
    }
}

void MainWindow::on_actionBossQuery_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageBoss);
        ui->tabWidgetBoss->setCurrentWidget(ui->tabBossQuery);
    }
}

void MainWindow::on_actionProfitQuery_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageBoss);
        ui->tabWidgetBoss->setCurrentWidget(ui->tabProfitQuery);
    }
}

void MainWindow::on_actionFinanceQuery_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageBoss);
        ui->tabWidgetBoss->setCurrentWidget(ui->tabFinanceQuery);
    }
}

void MainWindow::on_actionTicketAdjust_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageBoss);
        ui->tabWidgetBoss->setCurrentWidget(ui->tabTicketAdjust);
    }
}

void MainWindow::on_actionCompanyInfo_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pageSetting);
    ui->tabWidgetSetting->setCurrentWidget(ui->tabCompanyInfo);
}

void MainWindow::on_actionPersonalInfo_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pageSetting);
    ui->tabWidgetSetting->setCurrentWidget(ui->tabPersonalInfo);
}

void MainWindow::on_actionBatch_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageBoss);
        ui->tabWidgetBoss->setCurrentWidget(ui->tabBatch);
    }
}

void MainWindow::on_actionMessage_triggered()
{
    if(userService.checkUserCompany(this)){
        ui->stackedWidget->setCurrentWidget(ui->pageMessage);
    }
}

void MainWindow::on_pushButtonNewFormula_clicked()
{
    newFormulaWidget.showAndInit();
    productService.updateFormulaData(this);
}

void MainWindow::on_pushButtonCombine_clicked()
{
    Formula *formula = ui->tableViewCombineSplit->currentFormula();
    if(formula == nullptr){
        QMessageBox::warning(this, "警告", "未选择公式！");
        return;
    }

    combineWidget.initWithCombineId(formula->formulaBase->combineId);
}

void MainWindow::on_pushButtonSplit_clicked()
{
    Formula *formula = ui->tableViewCombineSplit->currentFormula();
    if(formula == nullptr){
        QMessageBox::warning(this, "警告", "未选择公式！");
        return;
    }

    splitWidget.initWithCombineId(formula->formulaBase->combineId);
}

void MainWindow::on_labelBtnAdd_clicked()
{
    if(!ui->lineEditReceiptAccount->text().isEmpty() && ui->lineEditReceiptAccount1->isHidden()){
        ui->lineEditReceiptAccount1->show();
        return;
    }

    if(!ui->lineEditReceiptAccount1->text().isEmpty() && ui->lineEditReceiptAccount2->isHidden()){
        ui->lineEditReceiptAccount2->show();
        return;
    }

    if(!ui->lineEditReceiptAccount2->text().isEmpty() && ui->lineEditReceiptAccount3->isHidden()){
        ui->lineEditReceiptAccount3->show();
        return;
    }

    if(!ui->lineEditReceiptAccount3->text().isEmpty() && ui->lineEditReceiptAccount4->isHidden()){
        ui->lineEditReceiptAccount4->show();
        return;
    }
}

void MainWindow::on_pushButtonNewProduct_clicked()
{
    if(User::getCompanyId().isEmpty()){
        QMessageBox::information(this, "信息", "您还没有加入企业！");
        return;
    }
    newProductWidget.setDirectory(ui->treeViewProduct->primaryDirectoryList(), ui->treeViewProduct->secondaryDirectoryList());
    newProductWidget.setCurrentDirectory(ui->treeViewProduct->selectedPrimaryDirectory(), ui->treeViewProduct->selectedSecondaryDirectory());
    newProductWidget.showAndClear();
    productService.updateProductData(this, ui->tableViewProduct);
}

void MainWindow::on_pushButtonEditProduct_clicked()
{
    if(User::getCompanyId().isEmpty()){
        QMessageBox::information(this, "信息", "您还没有加入企业！");
        return;
    }
    Product *product = ui->tableViewProduct->currentProduct();
    if(product != nullptr)
    {
        updateProductWidget.setDirectory(ui->treeViewProduct->primaryDirectoryList(), ui->treeViewProduct->secondaryDirectoryList());
        updateProductWidget.initWithProduct(product);
        updateProductWidget.exec();
        productService.updateProductData(this, ui->tableViewProduct);
    }else{
        QMessageBox::warning(this, "警告", "请先选择商品！");
    }
}

void MainWindow::on_pushButtonChangePwd_clicked()
{
    changePasswordWidget.setPasswordType(Tools::LoginPassword);
    changePasswordWidget.exec();
}

void MainWindow::on_pushButtonChangeOpPwd_clicked()
{
    changePasswordWidget.setPasswordType(Tools::OperatePassword);
    changePasswordWidget.exec();
}

void MainWindow::on_pushButtonSaveUser_clicked()
{
    userService.saveUser(
                this,
                ui->lineEditNickName->text(),
                ui->lineEditPosition->text(),
                ui->lineEditTel->text(),
                ui->lineEditMobile->text(),
                ui->lineEditQQ->text(),
                ui->lineEditWechat->text());
}

void MainWindow::on_pushButtonNewCompany_clicked()
{
    if(userService.inputOperatePassword(this)){
        companyService.newCompany(this, ui->lineEditCompanyName->text(), ui->lineEditContact->text());
    }
}

void MainWindow::on_pushButtonSaveCompany_clicked()
{
    QString accounts;
    QString account0 = ui->lineEditReceiptAccount->text();
    accounts.append(account0);
    if(ui->lineEditReceiptAccount1->isVisible()){
        QString account1 = ui->lineEditReceiptAccount1->text();
        if(!account1.isEmpty()) accounts.append("#").append(account1);
    }
    if(ui->lineEditReceiptAccount2->isVisible()){
        QString account2 = ui->lineEditReceiptAccount2->text();
        if(!account2.isEmpty()) accounts.append("#").append(account2);
    }
    if(ui->lineEditReceiptAccount3->isVisible()){
        QString account3 = ui->lineEditReceiptAccount3->text();
        if(!account3.isEmpty()) accounts.append("#").append(account3);
    }
    if(ui->lineEditReceiptAccount4->isVisible()){
        QString account4 = ui->lineEditReceiptAccount4->text();
        if(!account4.isEmpty()) accounts.append("#").append(account4);
    }
    companyService.updateCompany(
                this,
                Company::getCompanyId(),
                ui->lineEditTaxRate->text(),
                ui->lineEditCompanyName->text(),
                ui->lineEditContact->text(),
                ui->lineEditCompanyTel->text(),
                ui->lineEditFax->text(),
                ui->lineEditWebsite->text(),
                ui->lineEditEmail->text(),
                ui->lineEditProvince->text(),
                ui->lineEditCity->text(),
                ui->lineEditDistrict->text(),
                ui->lineEditAddress->text(),
                accounts,
                ui->lineEditIntroduction->text(),
                ui->lineEditTicketCompanyName->text(),
                ui->lineEditTaxNum->text(),
                ui->lineEditBank->text(),
                ui->lineEditTicketAccount->text(),
                ui->lineEditTicketTel->text(),
                ui->lineEditTicketAddress->text());
}

void MainWindow::on_pushButtonUpdateProductData_clicked()
{
    on_pushButtonProductClearQuery_clicked();
    ui->tableViewProduct->clear();
    productService.updateProductData(this, ui->tableViewProduct);
}

void MainWindow::on_pushButtonJoinCompany_clicked()
{
    if(userService.inputOperatePassword(this)){
        joinCompanyWidget.showAndClear();
    }
}

void MainWindow::on_lineEditProductOverallQuery_textChanged(const QString &text)
{
    productService.queryProducts(
                ui->tableViewProduct,
                ui->treeViewProduct,
                ui->comboBoxProduct->currentIndex(),
                text,
                ui->lineEditProductTypeQuery->text(),
                ui->lineEditProductNameQuery->text());
}

void MainWindow::on_lineEditProductTypeQuery_textChanged(const QString &text)
{
    productService.queryProducts(
                ui->tableViewProduct,
                ui->treeViewProduct,
                ui->comboBoxProduct->currentIndex(),
                ui->lineEditProductOverallQuery->text(),
                text,
                ui->lineEditProductNameQuery->text());
}

void MainWindow::on_lineEditProductNameQuery_textChanged(const QString &text)
{
    productService.queryProducts(
                ui->tableViewProduct,
                ui->treeViewProduct,
                ui->comboBoxProduct->currentIndex(),
                ui->lineEditProductOverallQuery->text(),
                ui->lineEditProductTypeQuery->text(),
                text);
}

void MainWindow::on_pushButtonProductClearQuery_clicked()
{
    ui->comboBoxProduct->setCurrentIndex(0);
    ui->lineEditProductOverallQuery->clear();
    ui->lineEditProductTypeQuery->clear();
    ui->lineEditProductNameQuery->clear();
}

void MainWindow::on_pushButtonNewFinance_clicked()
{
    FinanceItem *financeItem = ui->tableViewFinanceKeep->currentFinanceItem();

    if(financeItem == nullptr){
        QMessageBox::warning(this, "警告", "未选择财务科目！");
        return;
    }

    newFinanceWidget.showWithFinanceItem(financeItem);
}

void MainWindow::on_pushButtonFinanceSubjectAdd_clicked()
{
    addFinanceSubject.setDirectory(ui->treeViewFinance->secondaryDirectoryList());
    addFinanceSubject.setCurrentDirectory(
                ui->treeViewFinance->selectedPrimaryDirectory(),
                ui->treeViewFinance->selectedSecondaryDirectory());
    addFinanceSubject.exec();
}

void MainWindow::on_pushButtonFinanceSubjectEdit_clicked()
{
    FinanceItem *financeItem = ui->tableViewFinanceKeep->currentFinanceItem();

    if(financeItem == nullptr){
        QMessageBox::warning(this, "警告", "未选择财务科目！");
        return;
    }

    editFinanceSubject.setDirectory(ui->treeViewFinance->secondaryDirectoryList());
    editFinanceSubject.showWithFinanceItem(financeItem);
    ui->tableViewFinanceKeep->getFinanceItems();
}

void MainWindow::on_pushButtonImportClient_clicked()
{
    if(userService.inputOperatePassword(this)){
        uploadWidget.setWidgetType(1);
        uploadWidget.showAndInit();
    }
}

void MainWindow::on_pushButtonImportGiver_clicked()
{
    if(userService.inputOperatePassword(this)){
        uploadWidget.setWidgetType(2);
        uploadWidget.showAndInit();
    }
}

void MainWindow::on_pushButtonImportProduct_clicked()
{
    if(userService.inputOperatePassword(this)){
        uploadWidget.setWidgetType(0);
        uploadWidget.showAndInit();
    }
}

void MainWindow::on_pushButtonUpdateFormula_clicked()
{
    productService.updateFormulaData(this);
}

void MainWindow::on_pushButtonProductPlanNew_clicked()
{
    ui->tableViewProductPlan->clear();
    ui->tableViewProductPlan->queryPlanProducts();
}

void MainWindow::on_pushButtonProductCountClear_clicked()
{
    ui->tableViewProductCount->clear();
}

void MainWindow::on_pushButtonProductCountSubmit_clicked()
{
    if(!userService.inputOperatePassword(this)){
        return;
    }

    QList<Product*> products = ui->tableViewProductCount->currentProducts();
    if(products.size() == 0){
        QMessageBox::warning(this, "警告", "请先选择商品进行盘点！");
    }else{
        productService.countProduct(this, ui->pushButtonProductCountSubmit, ui->tableViewProductCount->currentProducts());
    }
}

void MainWindow::on_pushButtonProductLibraryStoreOut_clicked()
{
    if(userService.inputOperatePassword(this) == false){
        return;
    }
    productService.sanbaoMove(this, ui->pushButtonProductLibraryStoreOut, ui->tableViewProductLibrary->currentProducts(), Product::SanBaoMoveOut);
}

void MainWindow::on_pushButtonProductLibraryStoreIn_clicked()
{
    if(userService.inputOperatePassword(this) == false){
        return;
    }
    productService.sanbaoMove(this, ui->pushButtonProductLibraryStoreIn, ui->tableViewProductLibrary->currentProducts(), Product::SanBaoMoveIn);
}

void MainWindow::on_pushButtonSaleHistoryClear_clicked()
{
    this->saleHistorySelectedProduct = nullptr;
    this->saleHistorySelectedUserRelation = nullptr;

    ui->lineEditSaleHistoryClientName->clear();
    ui->lineEditSaleHistoryContact->clear();
    ui->lineEditSaleHistoryTel->clear();
    ui->lineEditSaleHistoryProductName->clear();
    ui->lineEditSaleHistoryProductType->clear();
    ui->lineEditSaleHistoryProductUnit->clear();
    ui->tableViewHistoryProductSale->clear();
}

void MainWindow::on_pushButtonBossUpdateCompanyData_clicked()
{
    companyService.updateCompanyData(this, true);
}

void MainWindow::on_pushButtonMessageUpdateData_clicked()
{
    messageService.getMessages(this);
}

void MainWindow::on_comboBoxMessageType_currentIndexChanged(int index)
{
    on_pushButtonMessageClear_clicked();

    if(index == 0){
        ui->labelMessageClientName->setText("客户名称");
    }else{
        ui->labelMessageClientName->setText("供应商名称");
    }
    ui->pushButtonMessageList->setCurrentMenuIndex(index);
}

void MainWindow::on_pushButtonMessageClear_clicked()
{
    ui->lineEditMessageClientName->clear();
    ui->lineEditMessageContact->clear();
    ui->lineEditMessageTel->clear();
    this->messageSelectedUserRelation = nullptr;

    ui->tableViewMessage->showData(
                this->messageSelectedUserRelation,
                ui->comboBoxMessageType->currentIndex()+1);
}

void MainWindow::on_pushButtonFinanceRefresh_clicked()
{
    ui->tableViewFinanceKeep->getFinanceItems();
}

void MainWindow::on_comboBoxTicketAdjustType_currentIndexChanged(int index)
{
    if(index == 0){
        adjustTicketUserPicker.setIsShowPlatformUser(true);
        ui->pushButtonTicketAdjustMoneyImport->setVisible(false);
        ui->pushButtonTicketAdjustTicketImport->setVisible(false);
        ui->labelTicketAdjustClientName->setText("客户名称");
        ui->labelTicketAdjustTicketOld->setText("应开发票：");
        ui->labelTicketAdjustTicketOldValue->setText("0.00");
        ui->labelTicketAdjustTicketTotal->setText("调整后应开发票：");
        ui->labelTicketAdjustTicketTotalValue->setText("0.00");
        ui->labelTicketAdjustMoneyOld->setText("应收货款");
        ui->labelTicketAdjustMoneyOldValue->setText("0.00");
        ui->labelTicketAdjustMoneyTotal->setText("调整后应收货款");
        ui->labelTicketAdjustMoneyTotalValue->setText("0.00");
    }else{
        adjustTicketUserPicker.setIsShowPlatformUser(false);
        ui->pushButtonTicketAdjustMoneyImport->setVisible(true);
        ui->pushButtonTicketAdjustTicketImport->setVisible(true);
        ui->labelTicketAdjustClientName->setText("供应商名称");
        ui->labelTicketAdjustTicketOld->setText("应收发票：");
        ui->labelTicketAdjustTicketOldValue->setText("0.00");
        ui->labelTicketAdjustTicketTotal->setText("调整后应收发票：");
        ui->labelTicketAdjustTicketTotalValue->setText("0.00");
        ui->labelTicketAdjustMoneyOld->setText("应付货款");
        ui->labelTicketAdjustMoneyOldValue->setText("0.00");
        ui->labelTicketAdjustMoneyTotal->setText("调整后应付货款");
        ui->labelTicketAdjustMoneyTotalValue->setText("0.00");
    }

    ui->lineEditTicketAdjustClientName->clear();
    ui->lineEditTicketAdjustContact->clear();
    ui->lineEditTicketAdjustTel->clear();
    adjustTicketUserRelation = nullptr;
}

void MainWindow::on_pushButtonTicketAdjustQuery_clicked()
{
    if(adjustTicketUserRelation == nullptr){
        QMessageBox::warning(this, "警告", "未选择客户或供应商！");
        return;
    }

    ui->lineEditTicketAdjustTicketChangeValue->setText("0.00");
    ui->lineEditTicketAdjustTicketChangeValue->setReadOnly(false);
    ui->lineEditTicketAdjustMoneyChangeValue->setText("0.00");
    ui->lineEditTicketAdjustMoneyChangeValue->setReadOnly(false);
    if(ui->comboBoxTicketAdjustType->currentIndex() == 0){
        ui->labelTicketAdjustTicketOldValue->setText(QString::number(adjustTicketUserRelation->ticketOut, 'f', 2));
        ui->labelTicketAdjustTicketTotalValue->setText(QString::number(adjustTicketUserRelation->ticketOut, 'f', 2));
        ui->labelTicketAdjustMoneyOldValue->setText(QString::number(adjustTicketUserRelation->moneyIn, 'f', 2));
        ui->labelTicketAdjustMoneyTotalValue->setText(QString::number(adjustTicketUserRelation->moneyIn, 'f', 2));
    }else{
        ui->labelTicketAdjustTicketOldValue->setText(QString::number(adjustTicketUserRelation->ticketIn, 'f', 2));
        ui->labelTicketAdjustTicketTotalValue->setText(QString::number(adjustTicketUserRelation->ticketIn, 'f', 2));
        ui->labelTicketAdjustMoneyOldValue->setText(QString::number(adjustTicketUserRelation->moneyOut, 'f', 2));
        ui->labelTicketAdjustMoneyTotalValue->setText(QString::number(adjustTicketUserRelation->moneyOut, 'f', 2));
    }
}

void MainWindow::on_pushButtonTicketAdjustClear_clicked()
{
    ui->lineEditTicketAdjustClientName->clear();
    ui->lineEditTicketAdjustContact->clear();
    ui->lineEditTicketAdjustTel->clear();
    adjustTicketUserRelation = nullptr;
    ui->lineEditTicketAdjustTicketChangeValue->setText("0.00");
    ui->lineEditTicketAdjustTicketChangeValue->setReadOnly(true);
    ui->lineEditTicketAdjustMoneyChangeValue->setText("0.00");
    ui->lineEditTicketAdjustMoneyChangeValue->setReadOnly(true);
    ui->labelTicketAdjustTicketOldValue->setText("0.00");
    ui->labelTicketAdjustTicketTotalValue->setText("0.00");
    ui->labelTicketAdjustMoneyOldValue->setText("0.00");
    ui->labelTicketAdjustMoneyTotalValue->setText("0.00");
}

void MainWindow::on_lineEditTicketAdjustTicketChangeValue_editingFinished()
{
    if(adjustTicketUserRelation == nullptr){
        return;
    }
    double adjustValue = ui->lineEditTicketAdjustTicketChangeValue->text().toDouble();
    QString adjustValueStr = QString::number(adjustValue, 'f', 2);
    ui->lineEditTicketAdjustTicketChangeValue->setText(adjustValueStr);
    QString adjustRes;
    if(ui->comboBoxTicketAdjustType->currentIndex() == 0){
        adjustRes = QString::number(adjustTicketUserRelation->ticketOut+adjustValue, 'f', 2);

    }else{
        adjustRes = QString::number(adjustTicketUserRelation->ticketIn+adjustValue, 'f', 2);
    }
    ui->labelTicketAdjustTicketTotalValue->setText(QString("%1").arg(adjustRes));
}

void MainWindow::on_lineEditTicketAdjustMoneyChangeValue_editingFinished()
{
    if(adjustTicketUserRelation == nullptr){
        return;
    }
    double adjustValue = ui->lineEditTicketAdjustMoneyChangeValue->text().toDouble();
    QString adjustValueStr = QString::number(adjustValue, 'f', 2);
    ui->lineEditTicketAdjustMoneyChangeValue->setText(adjustValueStr);
    QString adjustRes;
    if(ui->comboBoxTicketAdjustType->currentIndex() == 0){
        adjustRes = QString::number(adjustTicketUserRelation->moneyIn+adjustValue, 'f', 2);
    }else{
        adjustRes = QString::number(adjustTicketUserRelation->moneyOut+adjustValue, 'f', 2);
    }
    ui->labelTicketAdjustMoneyTotalValue->setText(QString("%1").arg(adjustRes));
}

void MainWindow::on_pushButtonTicketAdjustTicketReset_clicked()
{
    ui->lineEditTicketAdjustTicketChangeValue->setText("0.00");
}

void MainWindow::on_pushButtonTicketAdjustMoneyReset_clicked()
{
    ui->lineEditTicketAdjustMoneyChangeValue->setText("0.00");
}

void MainWindow::on_pushButtonTicketAdjustTicketSubmit_clicked()
{
    if(userService.inputOperatePassword(this) == false){
        return;
    }
    userRelationService.adjustUserRelationFinance(
                this,
                ui->pushButtonTicketAdjustTicketSubmit,
                adjustTicketUserRelation,
                "",
                ui->lineEditTicketAdjustTicketChangeValue->text().toDouble(),
                0);
}

void MainWindow::on_pushButtonTicketAdjustMoneySubmit_clicked()
{
    if(userService.inputOperatePassword(this) == false){
        return;
    }
    userRelationService.adjustUserRelationFinance(
                this,
                ui->pushButtonTicketAdjustMoneySubmit,
                adjustTicketUserRelation,
                "",
                0,
                ui->lineEditTicketAdjustMoneyChangeValue->text().toDouble());
}

void MainWindow::on_pushButtonSaleHistoryQuery_clicked()
{
    dingdanService.getHistoryProducts(
                this,
                0,
                this->saleHistorySelectedUserRelation,
                this->saleHistorySelectedProduct);
}

void MainWindow::on_pushButtonSaleHistorySubmitChange_clicked()
{
    if(!userService.inputOperatePassword(this)){
        return;
    }

    productService.updateHistoryProduct(this, ui->tableViewHistoryProductSale->getEditedHistoryProducts(), 0);
}

void MainWindow::on_pushButtonPurchaseOrderSend_clicked()
{
    if(this->purchaseOrderSelectedUserRelation == nullptr){
        QMessageBox::warning(this, "警告", "未选择供应商！");
        return;
    }

    if(!userService.inputOperatePassword(this)){
        return;
    }
    QList<DingdanDetail*> details = ui->tableViewPurchaseOrder->getDingdanDetails();

    Dingdan *dingdan = new Dingdan();

    dingdan->targetUsername = this->purchaseOrderSelectedUserRelation->targetUsername;
    dingdan->targetCompanyId = this->purchaseOrderSelectedUserRelation->targetCompanyId;
    dingdan->type = Dingdan::PurchaseDingdan;
    dingdan->details = details;

    ui->pushButtonPurchaseOrderSend->setEnabled(false);
    dingdanService.calculateDingdan(this, ui->pushButtonPurchaseOrderSend, *dingdan);
}

void MainWindow::on_pushButtonFinanceQueryClear_clicked()
{
    lastFinanceQueryStartDate = Tools::getBaseDate();
    lastFinanceQueryEndDate = QDate::currentDate();
    ui->dateEditFinanceQueryStartTime->setDate(Tools::getBaseDate());
    ui->dateEditFinanceQueryEndTime->setDate(QDate::currentDate());
    ui->comboBoxFinanceQueryType1->setCurrentIndex(0);
    ui->comboBoxFinanceQueryType2->setCurrentIndex(0);
}

void MainWindow::on_pushButtonFinanceQueryStart_clicked()
{
    financeService.financeQuery(
                this,
                ui->comboBoxFinanceQueryType1->currentIndex(),
                ui->comboBoxFinanceQueryType2->currentIndex(),
                ui->dateEditFinanceQueryStartTime->text(),
                ui->dateEditFinanceQueryEndTime->text());
}

void MainWindow::on_comboBoxFinanceQueryType1_currentIndexChanged(int index)
{
    ui->comboBoxFinanceQueryType2->clear();
    ui->comboBoxFinanceQueryType2->addItems(financeQueryTypes[index]);

    ui->tableViewFinanceQuery->setType(index);
    ui->tableViewFinanceQuery->clear();

    ui->pushButtonFinanceQueryList->setCurrentMenuIndex(index);
}

void MainWindow::on_pushButtonBossQueryTicketCount_clicked()
{
    homeCountWidget.setWidgetType(HomeCountWidget::TicketCount);
    homeCountWidget.exec();
    companyService.updateCompanyData(this, false);
}

void MainWindow::on_pushButtonBossQueryMoneyCount_clicked()
{
    homeCountWidget.setWidgetType(HomeCountWidget::MoneyCount);
    homeCountWidget.exec();
    companyService.updateCompanyData(this, false);
}

void MainWindow::on_pushButtonTicketAdjustTicketImport_clicked()
{
    messagePicker.setTicketAdjustType(ui->comboBoxTicketAdjustType->currentIndex()*2);
    messagePicker.showAndInit(ui->pushButtonTicketAdjustTicketImport);
}

void MainWindow::on_pushButtonTicketAdjustMoneyImport_clicked()
{
    messagePicker.setTicketAdjustType(ui->comboBoxTicketAdjustType->currentIndex()*2+1);
    messagePicker.showAndInit(ui->pushButtonTicketAdjustMoneyImport);
}

void MainWindow::on_dateEditFinanceQueryStartTime_dateChanged(const QDate &date)
{
    QDate endDate = ui->dateEditFinanceQueryEndTime->date();
    if(date > endDate){
        ui->dateEditFinanceQueryStartTime->setDate(lastFinanceQueryStartDate);
    }else{
        lastFinanceQueryStartDate = date;
        ui->dateEditFinanceQueryStartTime->setDate(date);
    }
}

void MainWindow::on_dateEditFinanceQueryEndTime_dateChanged(const QDate &date)
{
    QDate startDate = ui->dateEditFinanceQueryStartTime->date();
    if(date < startDate){
        ui->dateEditFinanceQueryEndTime->setDate(lastFinanceQueryEndDate);
    }else{
        lastFinanceQueryEndDate = date;
        ui->dateEditFinanceQueryEndTime->setDate(date);
    }
}

void MainWindow::on_comboBoxProduct_currentIndexChanged(int index)
{
    productService.queryProducts(
                ui->tableViewProduct,
                ui->treeViewProduct,
                index,
                ui->lineEditProductOverallQuery->text(),
                ui->lineEditProductTypeQuery->text(),
                ui->lineEditProductNameQuery->text());
}

void MainWindow::on_lineEditTicketAdjustTicketChangeValue_textEdited(const QString &text)
{
    Q_UNUSED(text)
    ui->lineEditTicketAdjustMoneyChangeValue->clear();
}

void MainWindow::on_lineEditTicketAdjustMoneyChangeValue_textEdited(const QString &text)
{
    Q_UNUSED(text)
    ui->lineEditTicketAdjustTicketChangeValue->clear();
}
